import pandas as pd
from rich.console import Console
from rich.table import Table
from rich import box

def analysis_csv(csv_path):
    data = pd.read_csv(csv_path)
    data = data.to_dict(orient="records")
    # 统计分析
    total_calls = len(data)
    customer_service_negative = sum(1 for d in data if "不符合要求" in d["客服情绪评估"])
    user_negative = sum(1 for d in data if "不满意" in d["用户情绪评估"])
    issue_unresolved = sum(1 for d in data if "未得到解决" in d["用户问题解决评估"])
    customer_service_and_user_negative = sum(1 for d in data if "不符合要求" in d["客服情绪评估"] and "不满意" in d["用户情绪评估"])
    customer_service_negative_and_issue_unresolved = sum(1 for d in data if "不符合要求" in d["客服情绪评估"] and "未得到解决" in d["用户问题解决评估"])
    # 使用 rich 打印结果
    console = Console()
    # 创建表格
    table = Table(title="通话统计信息", box=box.MINIMAL_DOUBLE_HEAD, show_header=True, header_style="bold magenta")
    table.add_column("统计项", style="cyan")
    table.add_column("值", style="green")
    # 添加数据到表格
    table.add_row("总通话数", str(total_calls))
    table.add_row("客服情绪不符合要求占比", f"{customer_service_negative/total_calls:.2%}", style="bold red")
    table.add_row("客户情绪异常占比（全过程）", f"{user_negative/total_calls:.2%}")
    table.add_row("问题未解决占比", f"{issue_unresolved/total_calls:.2%}")
    table.add_row("客服异常且客户异常占比", f"{customer_service_and_user_negative/total_calls:.2%}")
    table.add_row("客服异常且问题未解决占比", f"{customer_service_negative_and_issue_unresolved/total_calls:.2%}")
    table.add_row("数据周期", f"2024-10-14")
    table.add_row("平均数据处理时间", f"98.5s")
    # 打印表格
    console.print(table)
    console.print(f"[red]注意：异常情绪包括但不限于：愤怒、焦虑、悲伤、厌恶等。[/red]")
    console.print(f"[red]注意：客户情绪异常占比指的是全过程中是否有出现过。[/red]")
    console.print(f"[green]表格来源：{csv_path}[/green]")
    console.print(f"[green]"+"*"*60+"[/green]")


if __name__ == "__main__":

    # 假设CSV文件的路径如下
    csv_file_1 = "outputs/output copy 2.csv"
    csv_file_2 = "outputs/output copy 3.csv"

    analysis_csv(csv_file_1)
    analysis_csv(csv_file_2)
    # 读取两个CSV文件
    df1 = pd.read_csv(csv_file_1)
    df2 = pd.read_csv(csv_file_2)

    # 合并两个DataFrame，以ID为键
    merged_df = pd.merge(df1, df2, on='ID', suffixes=('_1', '_2'))

    # 定义一个函数，检查两个列是否有异常
    def check_exception(col1, col2):
        _1 = ("不符合要求" in col1) and ("不符合要求" in col2)
        _2 = ("不满意" in col1) and ("不满意" in col2)
        _3 = ("未得到解决" in col1) and ("未得到解决" in col2)
        _4 = ("不规范" in col1) and ("不规范" in col2)
        return _1 or _2 or _3 or _4

    # 应用该函数到每一行，以确定是否异常
    merged_df['客服情绪异常'] = merged_df.apply(lambda row: check_exception(row['客服情绪评估_1'], row['客服情绪评估_2']), axis=1)
    merged_df['用户情绪异常'] = merged_df.apply(lambda row: check_exception(row['用户情绪评估_1'], row['用户情绪评估_2']), axis=1)
    merged_df['用户问题解决异常'] = merged_df.apply(lambda row: check_exception(row['用户问题解决评估_1'], row['用户问题解决评估_2']), axis=1)


    # 统计异常情况
    total_ids = len(merged_df)
    customer_service_exceptions = merged_df['客服情绪异常'].sum()
    user_emotion_exceptions = merged_df['用户情绪异常'].sum()
    issue_resolution_exceptions = merged_df['用户问题解决异常'].sum()
    # 统计客服情绪异常且问题未解决的数量
    customer_service_and_issue_unresolved = merged_df[(merged_df['客服情绪异常']) & (merged_df['用户问题解决异常'])].shape[0]
    # 统计客服情绪异常、用户情绪异常、问题未解决的数量
    all_exceptions = merged_df[(merged_df['客服情绪异常']) & (merged_df['用户情绪异常']) & (merged_df['用户问题解决异常'])].shape[0]

    # rich 好看的打印各分析结果
    console = Console()
    table = Table(title="通话异常情况统计", box=box.MINIMAL_DOUBLE_HEAD, show_header=True, header_style="bold magenta")
    table.add_column("统计项", style="cyan")
    table.add_column("值", style="green")
    table.add_row("总通话数", str(total_ids))
    table.add_row("客服情绪异常数", str(customer_service_exceptions), style="bold red")
    table.add_row("客服情绪异常占比", f"{customer_service_exceptions/total_ids:.2%}", style="bold red")
    table.add_row("用户情绪异常数", str(user_emotion_exceptions))
    table.add_row("用户情绪异常占比", f"{user_emotion_exceptions/total_ids:.2%}")
    table.add_row("用户问题解决异常数", str(issue_resolution_exceptions))
    table.add_row("用户问题解决异常占比", f"{issue_resolution_exceptions/total_ids:.2%}")
    table.add_row("客服异常且问题未解决数", str(customer_service_and_issue_unresolved), style="bold red")
    table.add_row("客服异常且问题未解决占比", f"{customer_service_and_issue_unresolved/total_ids:.2%}", style="bold red")
    table.add_row("客服异常、用户异常、问题未解决数", str(all_exceptions), style="bold red")
    table.add_row("客服异常、用户异常、问题未解决占比", f"{all_exceptions/total_ids:.2%}", style="bold red")
    console.print(table)
    console.print(f"[green]表格来源：{csv_file_1} 和 {csv_file_2}[/green]")

    # 打印客服异常数据样例
    console.print("\n[bold red]客服异常数据样例：[/bold red]")
    for idx, row in merged_df.iterrows():
        if row['客服情绪异常']:
            console.print(f"ID: {row['ID']}, [yellow]原因[/yellow]: {row['客服情绪原因_1']}")
        # 从./outputs/txt/<id>.txt中读取对话内容 在下面打印出来
        # with open(f"./outputs/txt/{row['ID']}.txt", "r", encoding="utf-8") as f:
        #     content = f.read()
        #     console.print(content)
            console.print(f"[yellow]\t点击查看对话内容: outputs/txt/{row['ID']}.txt [/yellow]")
            console.print(f"[yellow]\t点击试听音频: outputs/tmp_wav/{row['ID']}.wav [/yellow]")
    # 客服异常且问题未解决数据样例
    console.print("\n[bold red]客服异常且问题未解决数据样例：[/bold red]")
    for idx, row in merged_df.iterrows():
        if row['客服情绪异常'] and row['用户问题解决异常']:
            console.print(f"ID: {row['ID']}, [yellow]原因[/yellow]: {row['客服情绪原因_1']}")
